package phone.book;

import java.util.ArrayList;

import SMS.SMSMessaging;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class contactDetails extends Activity{
	
	ArrayList<String> contactsList = new ArrayList<String>();
	AlertDialog.Builder alert;
	String phoneNumber=null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        long id = getIntent().getExtras().getLong("contactId");
        refresh_contact_details(id);        

	}
	
	private void refresh_contact_details(long id) {
		contactsList = new ArrayList<String>();
		setContentView(R.layout.contactdetails);
        TextView tv1 = (TextView) findViewById(R.id.textView1);
        TextView tv2 = (TextView) findViewById(R.id.textView2);
        TextView tv3 = (TextView) findViewById(R.id.textView3);
        
        String id1= Long.toString(id);
       // tv1.setText(Long.toString(id));
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,    null,null, null, null);
        
       // Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
		if (cur.getCount() > 0) {
			        
		        	while (cur.moveToNext()) {
			        	id1 = cur.getString(cur.getColumnIndex(BaseColumns._ID));
			        	Long id2 = Long.parseLong(id1);
			        	if(id2 == id)
			        	{
			        		String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			        		//String phone = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone);
			        		tv1.setText(name);
			        		
			        		
			        		
			        		
		Log.d("error", cur.getColumnName(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
		String hasPhoneNumber = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
        if (Integer.parseInt(hasPhoneNumber) > 0) {
                  
                 // Build the Uri to query to table
               // Query the table
                 cur = getContentResolver().query(Phone.CONTENT_URI,
                         null, Phone.CONTACT_ID + "=?", new String[] {cur.getString(cur.getColumnIndex(BaseColumns._ID)) },
                         null);

                 int PhoneIdx = cur.getColumnIndex(Phone.DATA);
                
                 // Get the phone numbers from the contact
                 if (cur.moveToFirst()) {
                      
                     // Get a phone number
                     phoneNumber =cur.getString(PhoneIdx);
                    // int type = cur.getColumnIndexOrThrow(ContactsContract.Contacts.CONTENT_ITEM_TYPE);;
                     tv2.setText(phoneNumber);
                     contactsList.add(phoneNumber);
                  //   tv3.setText(mail);
                     Log.d("hi", "hi1");
                 }
             } else {
              Toast.makeText(this, "This contact doesn't have a phone number",
                         Toast.LENGTH_LONG).show();
             
             }
        Log.d("hi", "hi2");
        Cursor emailCur = cr.query( 
       			ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
       			null,
       			ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
       			new String[]{cur.getString(cur.getColumnIndex(BaseColumns._ID))}, null);
        Log.d("hi", "hi3");
       		while (emailCur.moveToFirst()) { 
       		    // This would allow you get several email addresses
       	            // if the email addresses were stored in an array
       			Log.d("hi", "hi4");
       		    String mail = emailCur.getString(
       	                      emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
       	 //	    String emailType = emailCur.getString(
       	 //                     emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
       	 	    Log.d("email", mail);
       	 	    tv3.setText(mail);
       	 	  //  tv4.setText(emailType);
       	 	} 
       	 	emailCur.close();
        		break;
			        	}
		        	}
			        	
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.contactdetailsmenu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		long id = getIntent().getExtras().getLong("contactId");
        String id2= Long.toString(id);
        Context c = this;
		switch(item.getItemId()){
			
			case R.id.call: call();return true;
			case R.id.contactSMS: sendSMS();return true;
			case R.id.editContact: editContact();return true;
			case R.id.deleteContact: deleteContact(id2,c);return true;
			default:return super.onOptionsItemSelected(item);
		}
	}
	
	private void call() {
			Log.d("Number", phoneNumber);
			if(phoneNumber.length()!=0)
			{
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_CALL);
				intent.setData(Uri.parse("tel:" + phoneNumber)); // set the Uri
				startActivity(intent);
			}
			else
			{
				Toast.makeText(this, "This contact doesn't have a phone number",
                        Toast.LENGTH_LONG).show();
			}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		long id = getIntent().getExtras().getLong("contactId");
		refresh_contact_details(id);
	}

	public void deleteContact(String id2, Context c) {
		
		ContentResolver cr = c.getContentResolver();
		Log.d("id_contact", id2);
		String id1 = BaseColumns._ID;
	
        //cr.query(uri, projection, selection, selectionArgs, sortOrder)
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,id1+"="+id2, null, null);
		while (cur.moveToNext()) { 
			try{ 
				String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
				
				Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
				System.out.println("The uri is " + uri.toString());
				cr.delete(uri, null, null);
				
				finish();
				}
			catch(Exception e){
				System.out.println(e.getStackTrace());
				}
			} 
		}
		
	public void sendSMS() {
		alert=new AlertDialog.Builder(this);
		alert.setTitle("SMS");
		if(contactsList.size()!=0){
	    	alert.setMessage("Enter Message");
	    	final EditText message=new EditText(this);
	    	alert.setView(message);
	    	alert.setPositiveButton("Send", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					String msg=message.getText().toString();
					SMSMessaging ob=new SMSMessaging(getApplicationContext());
					ArrayList<String> phno=contactsList;
					ob.sendMessage(phno,msg);
				}
			});
	    	alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {	
				public void onClick(DialogInterface dialog, int which) {
					
				}
			});
		}
		else
			alert.setMessage("No contacts to send SMS");
	    	alert.create().show();
	}

	private void editContact() {
		Intent i=new Intent(getApplicationContext(),edit_contact.class);
		i.putExtra("contactId", getIntent().getExtras().getLong("contactId"));
		startActivityForResult(i, 0);
	}
}
